﻿using Common;
using Common.XmlHandle;
using Network.UpdateData;
using SFJDManagement.SocketHandle;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace SFJDManagement
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class Win_Main_1 : Window
    {
        public static Win_Main_1 instance;
        public ClassBrigade brigade = new ClassBrigade();
        public ClassContact contact = new ClassContact();
        public List<ClassVehicle> vehicles = new List<ClassVehicle>();

		private Brush but_BorderColorDefault = null;
		private bool isInputErro = false;

        public Win_Main_1()
        {
            Runtime.Initialize();
            InitializeComponent();
            Title = "司法鉴定办公助手";
			but_BorderColorDefault = but_Brigade.BorderBrush;
            instance = this;
			Initialize();
        }

        private void Initialize()
        {
            Binding bind = new Binding();
            bind.Source = Runtime.config;
            bind.Path = new PropertyPath("UserName");
            textBlock.SetBinding(TextBlock.TextProperty, bind);
			DPHappenDate.DisplayDateEnd = DateTime.Now;
            DPEntrust.DisplayDateEnd = DateTime.Now;
            comboBox.ItemsSource = Enum.GetNames(typeof(EnumCaseType));
        }
        
        private void Main0_Loaded(object sender, RoutedEventArgs e)
        {
            DGVechicles.ItemsSource = vehicles;
            ServiceHelper server = new ServiceHelper();
            if (!server.IsServiceIsExisted(Runtime.serviceName))
            {
                Close();
            }
            else
            {
                if (!server.IsServiceStart(Runtime.serviceName))
                {
                    try
                    {
                        server.StartService(Runtime.serviceName);
                    }
                    catch
                    {
                        Close();
                    }
                }
            }
        }

        public Win_Brigade cBrigade;
        private void but_Brigade_Click(object sender, RoutedEventArgs e)
        {
            //cBrigade = new Win_Brigade(this);
            //cBrigade.Owner = this;
            //cBrigade.Visibility = Visibility.Visible;
            //Visibility = Visibility.Hidden;
        }

        private void expander_Expanded(object sender, RoutedEventArgs e)
        {
            
            exGrid0.Margin = new Thickness(-24, 24, 0, -(ActualHeight - 24 - 31));
        }

        private void Main0_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            exGrid0.Margin = new Thickness(-24, 24, 0, -(ActualHeight - 24 - 31));
            if(exGrid2.ActualWidth > 0)
            {
                exGrid2.Width = ActualWidth - exGrid1.ActualWidth - 14;
            }
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            if(exGrid2.ActualWidth == 0)
            {
                exGrid2.Width = ActualWidth - exGrid1.ActualWidth - 14;
                Thickness thick = new Thickness(30, 5, 0, 5);
                Binding bind = new Binding();
                bind.Source = Runtime.config;
                Label l1 = new Label();
                l1.FontSize = 16;
                l1.Content = "用户姓名：";
                exGrid2a.Children.Add(l1);
                TextBox tb1 = new TextBox();
                tb1.FontSize = 18;
                tb1.Height = 30;
                tb1.Width = 200;
                bind.Path = new PropertyPath("UserName");
                tb1.SetBinding(TextBox.TextProperty, bind);
                //tb.DataContext = config.UserName;
                exGrid2a.Children.Add(tb1);
                CheckBox cb2 = new CheckBox();
                cb2.Content = "  是否为服务器";
                cb2.IsChecked = Runtime.config.IsServer;
                cb2.FontSize = 18;
                cb2.Margin = thick;
                exGrid2a.Children.Add(cb2);
                CheckBox cb3 = new CheckBox();
                cb3.Content = "  是否管理员";
                cb3.IsChecked = Runtime.config.IsAdmin;
                cb3.FontSize = 18;
                cb3.Margin = thick;
                exGrid2a.Children.Add(cb3);
                CheckBox cb4 = new CheckBox();
                cb4.Content = "  是否可以自定义";
                cb4.IsChecked = Runtime.config.IsCustomize;
                cb4.FontSize = 18;
                cb4.Margin = thick;
                exGrid2a.Children.Add(cb4);
                CheckBox cb5 = new CheckBox();
                cb5.Content = "  是否仅查询模式";
                cb5.IsChecked = Runtime.config.IsQueryOnly;
                cb5.FontSize = 18;
                cb5.Margin = thick;
                exGrid2a.Children.Add(cb5);
                Label l2 = new Label();
                l2.Content = "接收文件的目录：";
                l2.FontSize = 16;
                exGrid2a.Children.Add(l2);
                Label l3 = new Label();
                l3.Content = "案件材料存放的目录：";
                l3.FontSize = 16;
                exGrid2a.Children.Add(l3);
                TextBox tb3 = new TextBox();
                tb3.FontSize = 18;
                tb3.Text = Runtime.config.OutPath2String();
                exGrid2a.Children.Add(tb3);
                
                Button saveConfig = new Button();
                saveConfig.Content = "保存";
                saveConfig.FontSize = 16;
                saveConfig.Height = 30;
                saveConfig.Margin = new Thickness(0, 30, 0, 0);
                saveConfig.Click += SaveConfig_Click;
                exGrid2a.Children.Add(saveConfig);
            }
            else
            {
                exGrid2a.Children.Clear();
                exGrid2.Width = 0;
            }
        }

        private void SaveConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Runtime.config = Runtime.xmlUsers.GetUser(Runtime.config.UserName);
                Runtime.xmlConfig.SetConfig(Runtime.config);
            }
            catch
            {
                Packet packet = new Packet(typeof(SC04RegisterUser).GetClient2ServerKey(), Runtime.config.UserGuid, Runtime.config.UserName);
                CSendMsg.SendMsgNoWait(packet.ToBytes());
                //CSendMsg.SendMsgNoWait("2050" + Runtime.config.UserName);
                new Thread(() =>
                {
                    Thread.Sleep(100);
                    int n = 0;
                    bool isNotDefind = false;
                    while ((isNotDefind = Runtime.xmlUsers.IsDefindUser(Runtime.config.UserName)) & n < 10)
                    {
                        Thread.Sleep(100);
                        n++;
                    }
                    if (isNotDefind)
                    {
                        Runtime.config.ToDefault();
                    }
                    else
                    {
                        Runtime.config = Runtime.xmlUsers.GetUser(Runtime.config.UserName);
                    }

                    Runtime.xmlConfig.SetConfig(Runtime.config);
                }).Start();
            }
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            if(exGrid2.ActualWidth == 0)
            {
                exGrid2.Width = ActualWidth - exGrid1.ActualWidth - 14;
                Label l1 = new Label();
                l1.FontSize = 20;
                l1.Content = "司法鉴定管理程序";
                exGrid2a.Children.Add(l1);
                Label l2 = new Label();
                l2.FontSize = 20;
                l2.Content = "用户：" + Runtime.institution;
                exGrid2a.Children.Add(l2);
                Label l3 = new Label();
                l3.FontSize = 20;
                l3.Content = "作者：吴戈";
                exGrid2a.Children.Add(l3);
                Label l4 = new Label();
                l4.FontSize = 20;
                l4.Content = "版本：" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                exGrid2a.Children.Add(l4);
                Label l5 = new Label();
                l5.FontSize = 20;
                l5.Content = "更新：" + System.IO.File.GetLastWriteTime(GetType().Assembly.Location).ToLongDateString();
                exGrid2a.Children.Add(l5);
            }
            else
            {
                exGrid2a.Children.Clear();
                exGrid2.Width = 0;
            }
        }

        private void tbContactName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (tbContactName.Text == null)
                return;
            contact.Name = tbContactName.Text;
            contact.Phone = Runtime.xmlContact.GetContact(brigade.Guid, contact.Name);
            if(contact.Phone != null)
            {
                tbContactPhone.Text = contact.Phone;
            }
            else
            {
                tbContactPhone.Text = null;
            }
        }

        private void tbContactPhone_LostFocus(object sender, RoutedEventArgs e)
        {
            ClassContact con = Runtime.xmlContact.GetContactByPhone(brigade.Guid.ToString(), tbContactPhone.Text);
            if (con != null)
            {
                tbContactName.Text = con.Name;
                contact = con;
            }
            else
            {
                if (tbContactPhone.Text != null && tbContactName.Text != null && brigade.Guid != null)
                {
                    if(tbContactPhone.Text != "" && tbContactName.Text != "")
                    {
                        contact.Brigade = brigade.Guid;
                        contact.Phone = tbContactPhone.Text;
                        Runtime.xmlContact.AddContact(contact);
                        Packet packet = new Packet(typeof(SC03RegisterContact).GetClient2ServerKey(), Runtime.config.UserGuid, contact.Coding2String());
                        CSendMsg.SendMsgNoWait(packet.ToBytes());
                        //new CSendMsg().SendMsgNoWait("2040" + contact.Coding2String());
                    }
                }
            }
        }

        private void expander_Collapsed(object sender, RoutedEventArgs e)
        {
            exGrid2a.Children.Clear();
            exGrid2.Width = 0;
            //System.Diagnostics.Debug.WriteLine("-------------------" + e.ToString() + "--------");
        }

        private void but_Register_Click(object sender, RoutedEventArgs e)
        {
            //Packet packet1 = new Packet(typeof(SC01RegisterDataReply).GetClient2ServerKey(), Runtime.config.UserGuid,
            //    "0♠SXXAGS20170101♠2♠a8c690ef-f56f-4798-bdad-08f619394280♠苏伟♠7903ca5b-216d-4777-b67b-f85ebb7a65b8♠2017/01/01 03:30♠2017/01/01♠2017/09/25 14:18:25♠陕A00000♣无♣无♣abc");
            //CSendMsg.SendMsgWait(packet1.ToBytes());
            //return;
            if (checkInput())
			{
				return;
			}
			try
			{
				but_Register.IsEnabled = false;
				ClassData dat = new ClassData();
                string happen0 = DPHappenDate.Text + " " + DPHappenHour.Text + ":" + DPHappenMin.Text;
                DateTime happen = Convert.ToDateTime(happen0);
                DateTime entrust = Convert.ToDateTime(DPEntrust.Text);
                string happ = happen.ToString("yyyyMMdd");
                dat.ID = 0;
                dat.Code = brigade.Code + happ.Replace(" ", "");
                dat.CaseType = comboBox.SelectedIndex + 1;
                dat.Brigade = brigade.Guid;
                dat.Contact = contact.Name;
                dat.User = Runtime.config.UserGuid;
                dat.TimeHappen = happen;
                dat.TimeEntrust = entrust;
                dat.TimeArrange = DateTime.Now;
                foreach (ClassVehicle vehicle in vehicles)
                {
                    if (vehicle != null)
                    {
                        if(vehicle.Number != null & vehicle.Brand != null & vehicle.Type != null)
                        {
                            if (vehicle.Number != "" & vehicle.Brand != "" & vehicle.Type != "")
                            {
                                dat.Vehicles.Add(vehicle);
                            }
                        }
                    }
                }
                Packet packet = new Packet(typeof(SC01RegisterDataReply).GetClient2ServerKey(), Runtime.config.UserGuid, dat.CodingToString());
                CSendMsg.SendMsgWait(packet.ToBytes());
                //new CSendMsg().SendMsgWait("2001" + dat.CodingToString());
            }
            catch
            {
				but_Register.IsEnabled = true;
				//Log.ToConsole("数据有错误！！" + "  " + ex.Message);
            }
        }

        private void button7_Click(object sender, RoutedEventArgs e)
        {
            Win_Ledger winLedger = new Win_Ledger(this);
            winLedger.Owner = this;
            Visibility = Visibility.Hidden;
            winLedger.Visibility = Visibility.Visible;
        }

		/// <summary>
		/// 检查用户输入的内容
		/// </summary>
		public bool checkInput()
		{
			isInputErro = false;	//重置变量
			//检查委托人
			if (but_Brigade.Content == null || but_Brigade.Content.ToString() == "选择委托人")
				InputErro(but_Brigade);
			else
				InputNoErro(but_Brigade);
			//检查发生日期
			if (DPHappenDate.Text == "")
				InputErro(DPHappenDate);
			else
				InputNoErro(DPHappenDate);
			//检查发生小时
			if (DPHappenHour.Text == null || DPHappenHour.Text == "")
				InputErro(DPHappenHour);
			else
				InputNoErro(DPHappenHour);
			//检查发生分钟
			if (DPHappenMin.Text == null || DPHappenMin.Text == "")  
				InputErro(DPHappenMin);
			else
				InputNoErro(DPHappenMin);
			//检查委托时间
			if (DPEntrust.Text == "")  
				InputErro(DPEntrust);
			else
				InputNoErro(DPEntrust);
			//检查联系人名字
			if (tbContactName.Text == null || tbContactName.Text == "" || !Regex.IsMatch(tbContactName.Text, "^[\u4E00-\u9FA5]{2,}$"))
				InputErro(tbContactName);
			else
				InputNoErro(tbContactName);
			//检查联系人电话
			if (brigade != null && brigade.Code != "LXSFJD" && tbContactPhone.Text == "")
				InputErro(tbContactPhone);
			else if (tbContactPhone.Text != "" && !Regex.IsMatch(tbContactPhone.Text, @"^(13|15|17|18)[0-9]{9}$"))
				InputErro(tbContactPhone);
			else
				InputNoErro(tbContactPhone);
			//检查事故类型
			if (comboBox.SelectedValue == null)
				InputErro(comboBox);
			else
				InputNoErro(comboBox);
			//检查是否输入了车辆号牌、品牌、型号
			if (vehicles.Count == 0)
			{
				InputErro(DGVechicles);
			}
			else
			{
				for (int i = vehicles.Count - 1; i >= 0; i--)	//删除空行，但是最后还有一行空行
				{
					if (vehicles[i].Number == null & vehicles[i].Brand == null & vehicles[i].Type == null)
						vehicles.RemoveAt(i);
					DGVechicles.Items.Refresh();
				}
				for (int i = vehicles.Count - 1; i >= 0; i--)	//从倒数第二行向前检查
				{
					for(int j = 2; j >= 0; j--)
					{
						DataGridCell cell = DataGridDevelop.GetCell(DGVechicles, i, j);
						if (cell.Content.GetType().Equals(typeof(TextBlock)))
						{
							TextBlock tb = cell.Content as TextBlock;
							if(tb.Text == null || tb.Text == "")
								InputErro(cell);
							else
								InputNoErro(cell);
						}
					}
				}
				bool isChecked = false;
				foreach(ClassVehicle veh in vehicles)	//检查是否勾选鉴定项目
				{
					if(veh.Procj | veh.Procs | veh.Procy | veh .Profx | veh.Progc | veh.Prohj | veh.Projsy | veh.Pross | veh.Prosx)
						isChecked = true;
				}
				if (isChecked)
					InputNoErro(DGVechicles);
				else
					InputErro(DGVechicles);
			}
			return isInputErro;
		}
		
		/// <summary>
		/// 如果控件有错误，则把控件边框变为红色
		/// </summary>
		/// <param name="cc"></param>
		private void InputErro(Control cc)
		{
			cc.BorderBrush = Brushes.Red;
			isInputErro = true;
		}

		/// <summary>
		/// 如果控件没有错误，则控件边框不变；如果是修改后的结果，则把边框变为黑色
		/// </summary>
		/// <param name="cc"></param>
		private void InputNoErro(Control cc)
		{
			if(cc.BorderBrush == Brushes.Red)
			{
				cc.BorderBrush =  but_BorderColorDefault;
			}
		}

		/// <summary>
		/// 清空输入的数据, 委托处理
		/// </summary>
        public void resetData()
        {
            Dispatcher.Invoke(new Action(delegate {
                but_Brigade.Content = null;
                DPHappenDate.Text = null;
                DPHappenHour.Clear();
                DPHappenMin.Clear();
                DPEntrust.Text = null;
                tbContactName.Clear();
                tbContactPhone.Clear();
                comboBox.SelectedIndex = -1;
                vehicles = new List<ClassVehicle>();
                DGVechicles.ItemsSource = null;
                DGVechicles.ItemsSource = vehicles;
                brigade = new ClassBrigade();
                contact = new ClassContact();
                but_Register.IsEnabled = true;
            }));
            //Dispatcher.InvokeShutdown();
        }

        private void DPHappenHour_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (DPHappenHour.Text == null || DPHappenHour.Text == "")
            {
                DPHappenHour.Text = "0";
            }
            int t = int.Parse(DPHappenHour.Text);
            if (e.Delta > 0)
            {
                t++;
                DPHappenHour.Text = t.ToString();
            }
            else
            {
                t--;
                DPHappenHour.Text = t.ToString();
            }
        }

        private void DPHappenHour_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                int t = int.Parse(DPHappenHour.Text);
                if (t > 23)
                {
                    DPHappenHour.Text = "0";
                }
                else if (t < 0)
                {
                    DPHappenHour.Text = "23";
                }
            }
            catch
            {
                DPHappenHour.Clear();
            }
        }

        private void DPHappenMin_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                int t = int.Parse(DPHappenMin.Text);
                if (t > 59)
                {
                    DPHappenMin.Text = "0";
                }
                else if (t < 0)
                {
                    DPHappenMin.Text = "59";
                }
            }
            catch
            {
                DPHappenMin.Clear();
            }
        }

        private void DPHappenMin_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (DPHappenMin.Text == null || DPHappenMin.Text == "")
            {
                DPHappenMin.Text = "0";
            }
            int t = int.Parse(DPHappenMin.Text);
            if (e.Delta > 0)
            {
                t++;
                DPHappenMin.Text = t.ToString();
            }
            else
            {
                t--;
                DPHappenMin.Text = t.ToString();
            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            Win_Ledger winLedger = new Win_Ledger(this);
            winLedger.Owner = this;
            Visibility = Visibility.Hidden;
            winLedger.Visibility = Visibility.Visible;
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            //Win_Ledger winLedger = new Win_Ledger("edit");
            //winLedger.Owner = this;
            Win_Edit win_Edit = new Win_Edit(this);
            win_Edit.Owner = this;
            Visibility = Visibility.Hidden;
            win_Edit.Visibility = Visibility.Visible;
            //winLedger.Visibility = Visibility.Visible;
        }

		private void DPHappenDate_LostFocus(object sender, RoutedEventArgs e)
		{
			if(DPHappenDate.Text != "" && DPEntrust.Text == "")
			{
				DPEntrust.DisplayDateStart = DPHappenDate.DisplayDate;
			}
		}

		private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (comboBox.SelectedValue == null)
				return;
			if(comboBox.SelectedValue.ToString() == "车损鉴定")
			{
				DGVechicles.Columns[3].Visibility = Visibility.Hidden;
				DGVechicles.Columns[4].Visibility = Visibility.Hidden;
				DGVechicles.Columns[5].Visibility = Visibility.Hidden;
				DGVechicles.Columns[6].Visibility = Visibility.Visible;
				DGVechicles.Columns[7].Visibility = Visibility.Hidden;
				DGVechicles.Columns[8].Visibility = Visibility.Hidden;
				DGVechicles.Columns[9].Visibility = Visibility.Hidden;
				DGVechicles.Columns[10].Visibility = Visibility.Hidden;
				DGVechicles.Columns[11].Visibility = Visibility.Hidden;
			}
			else
			{
				DGVechicles.Columns[3].Visibility = Visibility.Visible;
				DGVechicles.Columns[4].Visibility = Visibility.Visible;
				DGVechicles.Columns[5].Visibility = Visibility.Visible;
				DGVechicles.Columns[6].Visibility = Visibility.Hidden;
				DGVechicles.Columns[7].Visibility = Visibility.Visible;
				DGVechicles.Columns[8].Visibility = Visibility.Visible;
				DGVechicles.Columns[9].Visibility = Visibility.Visible;
				DGVechicles.Columns[10].Visibility = Visibility.Visible;
				DGVechicles.Columns[11].Visibility = Visibility.Visible;
			}
		}

        private void but_Test_Click(object sender, RoutedEventArgs e)
        {
            //new Win_Account() { Owner = this}.Show();
            new Win_Main2() { Owner = this }.Show();
        }
    }
}
